import { getAjax, postAjax, putAjax, deleteAjax } from '@/utils/request'
import { Mutation, Action } from 'vuex'

export interface Role {
  roleId: number | null;
  roleName: string;
  roleKey: string;
  roleSort: number;
  enable: boolean;
  delFlag?: boolean;
  remark?: string;
  menuCheckStrictly?: boolean;
  menuIds?: Array<string>;
}

export interface StateType {
  data: Role;
}

export interface ModuleType {
  namespaced: boolean;
  state: StateType;
  mutations: {
    SET_DATA: Mutation<StateType>;
  };
  actions: {
    getList: Action<StateType, StateType>;
    addRole: Action<StateType, StateType>;
    getRole: Action<StateType, StateType>;
    updateRole: Action<StateType, StateType>;
    changeStatus: Action<StateType, StateType>;
    deleteRole: Action<StateType, StateType>;
  };
}

const storeModel: ModuleType = {
  namespaced: true,
  state: {
    data: {
      roleId: -1,
      roleName: '',
      roleKey: '',
      roleSort: 0,
      enable: false,
      delFlag: false,
      remark: '',
      menuCheckStrictly: false,
      menuIds: []
    }
  },
  mutations: {
    SET_DATA: (state, data) => {
      state.data = data
    }
  },
  actions: {
    getList(_, params) {
      return getAjax('/system/role/list', params)
    },
    addRole(_, data) {
      return postAjax('/system/role', data)
    },
    getRole({ commit }, roleId) {
      return new Promise((resolve, reject) => {
        if (roleId) {
          getAjax(`/system/role/${roleId}`, null).then((res: any) => {
            commit('SET_DATA', res.data)
            resolve(res)
          }).catch(err => { reject(err) })
        } else {
          commit('SET_DATA', null)
          resolve(null)
        }
      })
    },
    updateRole(_, data) {
      return putAjax('/system/role/', data)
    },
    changeStatus(_, data) {
      return putAjax('/system/role/changeStatus', data)
    },
    deleteRole(_, data) {
      return deleteAjax(`/system/role/${data}`, null)
    }
  }
}
export default storeModel
